package com.bwie.task;

import cn.hutool.core.bean.BeanUtil;
import com.bwie.es.EsUser;
import com.bwie.mapper.TbUserMapper;
import com.bwie.pojo.TbUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.data.elasticsearch.core.document.Document;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author 军哥
 * @version 1.0
 * @description: TODO
 * @date 2025/4/29 15:01
 */

@Component
@Slf4j
public class SyncUserTask {

    @Autowired
    TbUserMapper tbUserMapper;

    @Autowired
    ElasticsearchRestTemplate elasticsearchRestTemplate;


    /**
     * @description 每分钟同步一次mysql的用户到ES中(全量同步)
     * @params []
     * @return void
     * @author 军哥
     * @date 2025/4/29 15:09
     */

    @Scheduled(cron = "0 0/1 * * * ?")
    public void syncUser(){
        log.info("开始同步用户信息~~~~~~~~~~~~~~~~~");

        //-- 检查索引，如果索引不存在，则创建索引
        IndexOperations indexOps = elasticsearchRestTemplate.indexOps(EsUser.class);
        if(!indexOps.exists()) {
            // 索引不存在，创建索引
            log.info("索引不存在，创建索引");

            indexOps.create();

            // 创建索引映射
            Document mapping = indexOps.createMapping();
            indexOps.putMapping(mapping);
        }


        //-- 从MySQL数据库中读取用户数据

        List<TbUser> tbUsers = tbUserMapper.selectList(null);

        //-- 把用户数据存储到ES中
        for (TbUser tbUser : tbUsers) {
            EsUser esUser = BeanUtil.toBean(tbUser, EsUser.class);
            elasticsearchRestTemplate.save(esUser);
        }

        log.info("同步用户信息结束~~~~~~~~~~~~~~~~~");
    }

}
